//
//  LRSPlayerViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/19.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

let LRSGetSFApiName = "whoisme"

class LRSPlayerViewController: UIViewController {
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        get{
            return .lightContent
        }
    }

    var roomID: Int?
    var shenfen: String?
    var playerID: Int?
    
    convenience init(_ roomID: Int, shenfen: String?){
        self.init()
        self.roomID = roomID
        self.shenfen = shenfen
    }
    
    var roomIDLabel: UILabel!
    
    var playerCard: LRSPlayerCard!
    
    var readyView: UIScrollView!
    var roomIDInput: UITextField!
    var numSelector: LLCollection!
    
    var loadingView: LLFullScreenLoading!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.groupTableViewBackground
        
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        headView.backgroundColor = LRSThemeColor1
        view.addSubview(headView)
        
        let backBtn = UIButton(frame: CGRect(x: 8, y: 20, width: 44, height: 44))
        
        var attrStr = NSMutableAttributedString(string: "\u{e624}\n结束")
        attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 24)!, range: NSMakeRange(0, 1))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(2, 2))
        attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, 4))
        backBtn.setAttributedTitle(attrStr, for: .normal)
        backBtn.titleLabel?.numberOfLines = 0
        
        headView.addSubview(backBtn)
        backBtn.addTarget(self, action: #selector(LRSPlayerViewController.goBack), for: .touchUpInside)
        
        let infoLabel = UILabel(frame: CGRect(x: 64, y: 20, width: view.bounds.width - 80, height: 44))
        infoLabel.textColor = UIColor.white
        infoLabel.textAlignment = .right
        infoLabel.numberOfLines = 0
        
        let showStr = "请对自己的身份保密\nPlease keep your identity secret"
        attrStr = NSMutableAttributedString(string: showStr)
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, 9))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(9, showStr.characters.count - 9))
        
        infoLabel.attributedText = attrStr
        
        headView.addSubview(infoLabel)
        
        headView.addSubview(infoLabel)
        
        roomIDLabel = UILabel(frame: CGRect(x: 16, y: 72, width: view.bounds.width - 32, height: 20))
        roomIDLabel.textAlignment = .center
        roomIDLabel.textColor = UIColor.lightGray
        roomIDLabel.font = UIFont.systemFont(ofSize: 14)
        view.addSubview(roomIDLabel)
        roomIDLabel.text = "房间号: "
        
        playerCard = LRSPlayerCard(frame: CGRect(x: 16, y: 64+32, width: view.bounds.width - 32, height: view.bounds.width + 32 + 64))
        playerCard.center = CGPoint(x: view.center.x, y: view.center.y)
        view.addSubview(playerCard)
        playerCard.activeBtn.addTarget(self, action: #selector(LRSPlayerViewController.peekPlayer), for: .touchDown)
        playerCard.activeBtn.addTarget(self, action: #selector(LRSPlayerViewController.popPlayer), for: .touchUpInside)
        playerCard.activeBtn.addTarget(self, action: #selector(LRSPlayerViewController.popPlayer), for: .touchUpOutside)
        playerCard.alpha = 0
        
        readyView = UIScrollView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height-64))
        readyView.alwaysBounceVertical = true
        readyView.keyboardDismissMode = .onDrag
        readyView.backgroundColor = UIColor.groupTableViewBackground
        view.addSubview(readyView)
        
        roomIDInput = UITextField(frame: CGRect(x: 32, y: 72, width: view.bounds.width - 64, height: 44))
        roomIDInput.backgroundColor = UIColor.white
        roomIDInput.layer.cornerRadius = 8
        roomIDInput.layer.borderColor = UIColor.lightGray.cgColor
        roomIDInput.layer.borderWidth = 1
        roomIDInput.placeholder = "请输入房间号"
        roomIDInput.textAlignment = .center
        readyView.addSubview(roomIDInput)
        
        let selectNumLabel = UILabel(frame: CGRect(x: 0, y: 132, width: view.bounds.width, height: 20))
        selectNumLabel.textAlignment = .center
        selectNumLabel.text = "请选择你的玩家编号"
        readyView.addSubview(selectNumLabel)
        
        
        numSelector = LLCollection(frame: CGRect(x: 0, y: 160, width: 192, height: 144), row: 3, column: 4)
        numSelector.center.x = view.center.x
        readyView.addSubview(numSelector)
        
        for i in 0..<numSelector.items.count{
            numSelector.items[i].layer.cornerRadius = 18
            numSelector.items[i].backgroundColor = LRSThemeColor2
            numSelector.items[i].setTitle("\(i+1)", for: .normal)
            numSelector.items[i].setTitleColor(UIColor.white, for: .normal)
            numSelector.items[i].frame = CGRect(x: numSelector.items[i].frame.origin.x + 4, y: numSelector.items[i].frame.origin.y + 4, width: 36, height: 36)
            numSelector.items[i].tag = i
            numSelector.items[i].addTarget(self, action: #selector(LRSPlayerViewController.selectPlayerID(sender:)), for: .touchUpInside)
        }
        
        let submitBtn = UIButton(frame: CGRect(x: 32, y: 320, width: view.bounds.width - 64, height: 44))
        submitBtn.setTitle("完成", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        submitBtn.backgroundColor = LRSThemeColor2
        readyView.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(LRSPlayerViewController.LRSJoinGame), for: .touchUpInside)
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        view.addSubview(loadingView)
        loadingView.alpha = 0
        
//        let alert = UIAlertController(title: "请输入房间号", message: nil, preferredStyle: .alert)
//        alert.addTextField { (tf) in
//            tf.keyboardType = .numberPad
//        }
//        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
//        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (action) in
//            let input = alert.textFields?.first?.text
//            if input != nil{
//                self.LRSJoinGame(roomID: input!)
//                
//            }
//        }))
//        present(alert, animated: true, completion: nil)
    }
    
    func selectPlayerID(sender: UIButton){
        print("select player \(sender.tag+1)")
        playerID = sender.tag + 1
        for i in numSelector.items{
            i.backgroundColor = LRSThemeColor2
        }
        sender.backgroundColor = LRSThemeColor1
    }
    
    func LRSJoinGame(){
        if roomIDInput.text == ""{
            roomIDInput.becomeFirstResponder()
            return
        }
        roomID = Int(roomIDInput.text!)
        if roomID == nil{
            roomIDInput.becomeFirstResponder()
            return
        }
        roomIDInput.resignFirstResponder()
        if playerID == nil{
            let alert = UIAlertController(title: "请选择玩家编号", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
            return
        }
        
        let urlStr = "\(HJY_DOMAIN_NAME)/api/\(LRSGetSFApiName)?room=\(roomID!)&number=\(playerID!)"
        print(urlStr)
        let resq = URLRequest(url: URL(string: urlStr)!)
        
        loadingView.alpha = 1
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            DispatchQueue.main.async {
                self.loadingView.alpha = 0
            }
            if err != nil {
                print(err!)
                let alert = UIAlertController(title: "网络错误", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                return
            }
            do{
                print(String(data: data!, encoding: .utf8) ?? "data is not utf8 string")
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                let shenfenParam = jsonData?.object(forKey: "shenfen") as? String
                if shenfenParam != nil{
                    if shenfenParam == "该号码牌已经被获取,请确认你的号码" {
                        let alert = UIAlertController(title: "该号码牌已经被获取,请确认你的号码", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }else{
                        self.shenfen = shenfenParam
                        let roomID = jsonData?.object(forKey: "room") as? String
                        
                        if roomID != nil{
                            DispatchQueue.main.async {
                                self.readyView.alpha = 0
                                self.roomIDLabel.text = "房间号: \(roomID!)"
                                
                                self.playerCard.alpha = 1
                                self.playerCard.shenfen = self.shenfen
                                self.playerCard.id = self.playerID
                                if self.playerID != nil{
                                    self.playerCard.nickname = "\(self.playerID!)号玩家"
                                }
                                
                            }
                        }else{
                            throw NSError(domain: "a", code: 1, userInfo: nil) as Error
                        }
                    }
                    
                }else{
                    let alert = UIAlertController(title: "获取失败，请检查房间号", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    
                }
                
                
                
                
                
                
            }catch let ex{
                let alert = UIAlertController(title: "服务器错误", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                
                print(ex)
            }
        }.resume()

    }

    func goBack(){
        if shenfen != nil{
            let alert = UIAlertController(title: "确定退出？", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "不退出", style: .cancel, handler: nil))
            alert.addAction(UIAlertAction(title: "退出", style: .default, handler: {(action) in
                _ = self.navigationController?.popViewController(animated: true)
            }))
            self.present(alert, animated: true, completion: nil)
        }else{
            _ = navigationController?.popViewController(animated: true)
        }
        
    }
    
    func peekPlayer(){
        playerCard.characterView.alpha = 1
    }
    
    func popPlayer(){
        playerCard.characterView.alpha = 0
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
